<?php

namespace App\Models\Admin;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class WorkOrder extends Model
{
    protected $table_name='work_order';

    /* 带筛选条件获取问题列表 */
    public function getWorkOrderListWithFilter($fields)
    {
        $res = DB::table($this->table_name.' as p')
            ->select('p.*','m.name','wol.pic_list','wol.description','wol.extend','wol.created_at')
            ->leftJoin('member as m','m.id','=','p.u_id')
            ->leftJoin('work_order_log as wol',function ($join){
                $join->on('wol.id','=','p.log_id')
                    ->where('wol.cid',0);
            });
        if($fields['type']!=''){
            if($fields['type']==2){
                $res->where('p.type',2);
            }else{
                $res->where('p.type','<>',2);
            }
        }
        if(isset($fields['user_id']) && $fields['user_id']!=''){
            $res->where('p.u_id',$fields['user_id']);
        }
        if($fields['searchKey']!=''){
            $searchKey = $fields['searchKey'];
            $res->where(function ($query) use ($searchKey) {
                $query->where('m.name', 'LIKE', '%' . $searchKey . '%')
                    ->orwhere('m.mobile', 'LIKE', '%' . $searchKey . '%')
                    ->orwhere('m.email', 'LIKE', '%' . $searchKey . '%');
            });
        }
        $total = $res;
        $data['total'] = $total->count();
        if($data['total']<1){
            $data['rows'] = [];
            return $data;
        }
        $data['rows'] = $res->skip($fields['start'])->take($fields['pageSize'])->orderBy($fields['sortName'], $fields['sortOrder'])->get();
        $data['rows'] = json_decode(json_encode($data['rows']),true);
        return $data;
    }

    /* 添加工单 */
    public function workOrderInsert($data)
    {
        $data['created_at'] = Carbon::now();
        $data['updated_at'] = Carbon::now();
        $res = DB::table($this->table_name)->insert($data);
        if(!$res){
            return false;
        }
        return true;
    }

    /* 添加问题记录 */
    public function workOrderLogInsert($data)
    {
        $data['created_at'] = Carbon::now();
        $res_id = DB::table('work_order_log')->insertGetId($data);
        if(!$res_id){
            return false;
        }
        return $res_id;
    }

    /* 更新问题 */
    public function workOrderUpdate($id,$data)
    {
        $res = DB::table($this->table_name)->where('id',$id)->update($data);
        if(!$res){
            return false;
        }
        return true;
    }
}
